package semiProject_army.mvc.listener;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

import semiProject_army.mvc.action.ActionHandler;

@WebListener
public class MVCListener implements ServletContextListener {

	private static Map<String, Object> actionMap = new HashMap<>();
	
    public void contextDestroyed(ServletContextEvent sce)  { 
    	
    }

    public void contextInitialized(ServletContextEvent sce)  { 
    	System.out.println("MVC 초기화 시작...");
		String mvc2cfg = "/WEB-INF/mvc.properties";
		
		Properties p = new Properties();
		
		FileInputStream fis = null;
		BufferedInputStream bis = null;
		
		try {

			String cfgPath = 
					sce.getServletContext().getRealPath(mvc2cfg);
			
			fis = new FileInputStream(cfgPath);
			bis = new BufferedInputStream(fis);
			
			p.load(bis);
			
		} catch(Exception ex) {
			System.out.println("mvc.properties 처리중 오류발생!");
			ex.printStackTrace();
		} finally {
			if(bis != null) try{bis.close();}catch(Exception e){}
			if(fis != null) try{fis.close();}catch(Exception e){}
		}

		Iterator<Object> iter = p.keySet().iterator();
		
		while(iter.hasNext()) {
			
			String cmd = (String) iter.next();
			String actionName = (String) p.getProperty(cmd);
			
			try {

				Class<?> actionClass = Class.forName(actionName);
				
				ActionHandler actionObj = 
						(ActionHandler)actionClass.newInstance();
				
				actionMap.put(cmd, actionObj);
				System.out.println(cmd + " => " + actionClass);
				
			} catch(Exception ex) {
				System.out.println("액션클래스 초기화시 오류발생!!");
				ex.printStackTrace();
			} //while
			
			System.out.println("MVC 초기화 완료...");
		}
    }

	public static Map<String, Object> getActionMap() {
		return actionMap;
	}
	
}
